package com.houtai.service.admin;


import com.houtai.base.RetInfo;
import com.houtai.bean.TsJzAdmin;
import com.houtai.bean.dto.admin.AdminLogin;
import com.houtai.common.util.CommonUtil;
import com.houtai.common.util.LogUtils;
import com.houtai.common.util.MD5;
import com.houtai.dao.TsJzAdminDao;
import com.houtai.dao.TsJzAdminOperationDao;
import com.houtai.dao.TsJzRoleDao;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created by lizhun on 2017/7/28.
 */
@Service

public class AdminService {
    private static Logger logger = Logger.getLogger(AdminService.class);
    @Autowired
    private TsJzAdminDao tsJzAdminDao;

    @Autowired
    private TsJzRoleDao tsJzRoleDao;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TsJzAdminOperationDao tsJzAdminOperationDao;
    /**
     * @Purpose   登录
     * @param     adminLogin，request
     * @version   1.0
     * @author    李寻欢
     * @time      2018-07-09
     * @return    RetInfo
     */
    public RetInfo login(AdminLogin adminLogin, HttpServletRequest request) {
        String logInfo = this.getClass().getName() + ":login:";
        RetInfo retInfo = new RetInfo();
        logger.info("======" + logInfo + "begin======");
        try {
            if (redisTemplate.opsForValue().get(adminLogin.getSession_code()) != null) {
                TsJzAdmin tsJzAdmin = tsJzAdminDao.findAdminByName(adminLogin.getUser_name());
                if (tsJzAdmin != null ) {
                    String code = (String)redisTemplate.opsForValue().get(adminLogin.getSession_code());
                    if (adminLogin.getImg_code().toUpperCase().equals(code.toUpperCase())) {
                        if (tsJzAdmin.getUser_pass().equals(MD5.code(adminLogin.getUser_pass()))) {

                            tsJzAdmin.setLogin_ip(adminLogin.getLogin_ip());
                            retInfo.setMark("0");
                            retInfo.setTip("登录成功");
                            Map<String, Object> map = new HashMap<>();
                            String token = CommonUtil.getToken();
                            map.put("token", token);
                            redisTemplate.opsForValue().set(token, tsJzAdmin, 1, TimeUnit.DAYS);
                            retInfo.setObj(map);

                        } else {
                            retInfo.setMark("1");
                            retInfo.setTip("密码不对");
                        }
                    } else {
                        retInfo.setMark("2");
                        retInfo.setTip("验证码不对");
                    }
                } else {
                    retInfo.setMark("1");
                    retInfo.setTip("账号不存在");
                }
            } else {
                retInfo.setMark("1");
                retInfo.setTip("验证码失效");
            }

        } catch (Exception e) {
            logger.error("======error:" + e.toString() + "======");
            retInfo.setMark("-1");
            retInfo.setTip("系统错误");
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    /**
     * @Purpose   登录
     * @param     request
     * @version   1.0
     * @author    李寻欢
     * @time      2018-07-09
     * @return    RetInfo
     */
    public RetInfo login1(HttpServletRequest request) {
        String logInfo = this.getClass().getName() + ":login1:";
        RetInfo retInfo = new RetInfo();
        logger.info("======" + logInfo + "begin======");
        try {
            TsJzAdmin tsJzAdmin = tsJzAdminDao.findAdminByName("admin");
            if (tsJzAdmin != null ) {
                retInfo.setMark("0");
                retInfo.setTip("登录成功");
                String token = CommonUtil.getToken();
                redisTemplate.opsForValue().set(token, tsJzAdmin, 1, TimeUnit.DAYS);
                retInfo.setObj(token);
            } else {
                retInfo.setMark("1");
                retInfo.setTip("账号不存在");
            }




        } catch (Exception e) {
            logger.error("======error:" + e.toString() + "======");
            retInfo.setMark("-1");
            retInfo.setTip("系统错误");
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }
    public RetInfo findAdminPage(int current_page, int page_size, HttpServletRequest request) {
        String logInfo = this.getClass().getName() + ":findAdminPage:";
        RetInfo retInfo = new RetInfo();
        logger.info("======" + logInfo + "begin======");
        try {
            TsJzAdmin tsJzAdmin = (TsJzAdmin) redisTemplate.opsForValue().get(request.getParameter("token")) ;
            int total_record = tsJzAdminDao.findAllAdminSize(tsJzAdmin);//总条数
            if (total_record > 0) {
                Map<String, Object> map = CommonUtil.page(total_record, current_page, page_size);
                map.put("admin_id", tsJzAdmin.getAdmin_id());
                List<TsJzAdmin> tdHtAdminDtos = tsJzAdminDao.findAllAdminPage(map);
                for (int i =0 ; i < tdHtAdminDtos.size() ; i ++) {
                    tdHtAdminDtos.get(i).setRole_name(tsJzRoleDao.findRoleById(tdHtAdminDtos.get(i).getRole_id()).getRole_name());
                }
                map.put("admins", tdHtAdminDtos);
                map.put("currentPage", current_page);
                map.put("father_id", Integer.valueOf(request.getParameter("father_id")));
                retInfo.setMark("0");
                retInfo.setTip("成功");
                retInfo.setObj(map);
            } else {
                retInfo.setMark("1");
                retInfo.setTip("暂无您要查找的结果");
            }
        } catch (Exception e) {
            logger.error("======error:" + e.toString() + "======");
            retInfo.setMark("-1");
            retInfo.setTip("系统错误");
        }
        logger.info("======" + logInfo + "end======");

        return retInfo;
    }


    public RetInfo insertAdmin(TsJzAdmin tsJzAdmin, HttpServletRequest request) {
        String logInfo = this.getClass().getName() + ":insertAdmin:";
        RetInfo retInfo = new RetInfo();
        logger.info("======" + logInfo + "begin======");
        try {
            TsJzAdmin adminDto = tsJzAdminDao.findAdminByName(tsJzAdmin.getUser_name());
            tsJzAdmin.setUser_pass(MD5.code(tsJzAdmin.getUser_pass()));
            tsJzAdmin.setIs_valid(0);
            if (adminDto == null) {
                tsJzAdmin.setLogin_ip("0.0.0.0");
                tsJzAdmin.setReg_time(new Timestamp(System.currentTimeMillis()));
                tsJzAdmin.setLogin_time(new Date());
                tsJzAdminDao.insertAdmin(tsJzAdmin);
                retInfo.setMark("0");
                retInfo.setTip("创建成功.");
                LogUtils.AdminOperation(redisTemplate,tsJzAdminOperationDao,"创建了新的管理员账号,user_name:" + tsJzAdmin.getUser_name(),request);

            } else {
                if (adminDto.getIs_valid() == 0) {
                    retInfo.setMark("1");
                    retInfo.setTip("帐号已存在.");
                } else if (adminDto.getIs_valid() == 1) {
                    tsJzAdmin.setAdmin_id(adminDto.getAdmin_id());
                    tsJzAdminDao.updateAdmin(tsJzAdmin);
                    retInfo.setMark("0");
                    retInfo.setTip("创建成功.");
                    LogUtils.AdminOperation(redisTemplate,tsJzAdminOperationDao,"创建了新的管理员账号,user_name:" + tsJzAdmin.getUser_name(),request);
                }
            }


        } catch (Exception e) {
            logger.error("======error:" + e.toString() + "======");
            retInfo.setMark("-1");
            retInfo.setTip("系统错误");
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }


    public RetInfo updateAdmin(TsJzAdmin tsJzAdmin, HttpServletRequest request) {
        String logInfo = this.getClass().getName() + ":updateAdmin:";
        RetInfo retInfo = new RetInfo();
        logger.info("======" + logInfo + "begin======");
        try {
            TsJzAdmin adminDto = tsJzAdminDao.findAdminById(tsJzAdmin.getAdmin_id());
            if (adminDto != null) {
                TsJzAdmin admin = tsJzAdminDao.findAdminByName(tsJzAdmin.getUser_name());
                if (admin != null && admin.getAdmin_id() != tsJzAdmin.getAdmin_id()) {
                    retInfo.setMark("1");
                    retInfo.setTip("该用户名已存在.");
                } else {
                    tsJzAdmin.setUser_pass(MD5.code(tsJzAdmin.getUser_pass()));
                    tsJzAdmin.setIs_valid(0);
                    tsJzAdmin.setUser_name(tsJzAdmin.getUser_name());
                    tsJzAdmin.setPhone(tsJzAdmin.getPhone());
                    tsJzAdmin.setRole_id(tsJzAdmin.getRole_id());
                    tsJzAdminDao.updateAdmin(tsJzAdmin);
                    retInfo.setMark("0");
                    retInfo.setTip("修改成功.");
                    LogUtils.AdminOperation(redisTemplate,tsJzAdminOperationDao,"修改了user_neme=" + tsJzAdmin.getUser_name() + "的管理员账号",request);

                }
            } else {
                retInfo.setMark("1");
                retInfo.setTip("帐号不存在.");
            }


        } catch (Exception e) {
            logger.error("======error:" + e.toString() + "======");
            retInfo.setMark("-1");
            retInfo.setTip("系统错误");
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }


    public TsJzAdmin findAdminById(int admin_id, HttpServletRequest request) {
        String logInfo = this.getClass().getName() + ":findAdminById:";
        RetInfo retInfo = new RetInfo();
        TsJzAdmin admin = null;
        logger.info("======" + logInfo + "begin======");
        try {
            admin = tsJzAdminDao.findAdminById(admin_id);
        } catch (Exception e) {
            logger.error("======error:" + e.toString() + "======");
            retInfo.setMark("-1");
            retInfo.setTip("系统错误");
        }
        logger.info("======" + logInfo + "end======");
        return admin;
    }


    public RetInfo deleteAdmin(TsJzAdmin tsJzAdmin, HttpServletRequest request) {
        String logInfo = this.getClass().getName() + ":deleteAdmin:";
        RetInfo retInfo = new RetInfo();
        logger.info("======" + logInfo + "begin======");
        try {
            tsJzAdminDao.updateAdminValid(tsJzAdmin.getAdmin_id());
            retInfo.setMark("0");
            retInfo.setTip("成功.");
            LogUtils.AdminOperation(redisTemplate,tsJzAdminOperationDao,"删除了id=" + tsJzAdmin.getAdmin_id() + "的管理员账号",request);


        } catch (Exception e) {
            logger.error("======error:" + e.toString() + "======");
            retInfo.setMark("-1");
            retInfo.setTip("系统错误");
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }


    public RetInfo updateAdminPassword(TsJzAdmin tsJzAdmin, HttpServletRequest request) {
        String logInfo = this.getClass().getName() + ":updateAdminPassword:";
        RetInfo retInfo = new RetInfo();
        logger.info("======" + logInfo + "begin======");
        try {
            tsJzAdmin.setUser_pass(tsJzAdmin.getUser_pass());
            tsJzAdminDao.updateAdminPassword(tsJzAdmin);
            retInfo.setMark("0");
            retInfo.setTip("成功.");
            redisTemplate.opsForValue().set(request.getParameter("token"), tsJzAdmin, 1, TimeUnit.DAYS);
            LogUtils.AdminOperation(redisTemplate,tsJzAdminOperationDao,"修改了id=" + tsJzAdmin.getAdmin_id() + "的管理员密码",request);


        } catch (Exception e) {
            logger.error("======error:" + e.toString() + "======");
            retInfo.setMark("-1");
            retInfo.setTip("系统错误");
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }
}
